const http = require('http');
const url = require('url');
const querystring = require('querystring');
module.exports = {

    startHttpServer(port, interceptor) {
        const server = http.createServer(async(req, res) => {
            // 设置响应头，指定返回的内容类型为 JSON
            res.setHeader('Content-Type', 'application/json');
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS');
            res.setHeader('Access-Control-Allow-Headers', '*');

            if (req.method  == "OPTIONS") {
                res.statusCode = 200;
                res.end(JSON.stringify({result: 'ok'}));
                return;
            }
            const contentType = req.headers['content-type'];
            if (contentType === 'application/json'){
            }
            // 处理GET请求
            if (req.method === 'GET') {
                // if (pathname === '/api/data') {
                //     // 处理 /api/data GET 请求
                //     const responseData = {
                //         message: 'GET request received',
                //         data: parsedUrl.query
                //     };
                //     res.writeHead(200, { 'Content-Type': 'application/json' });
                //     res.end(JSON.stringify(responseData));
                // } else {
                //     // 处理其他路径的GET请求
                //     res.writeHead(404, { 'Content-Type': 'text/plain' });
                //     res.end('Not Found');
                // }
                try {
                    const parsedUrl = url.parse(req.url);
                    const path = parsedUrl.pathname;
                    const query = querystring.parse(parsedUrl.query);
                    let options = {query: query, path: path, req: req, res: res}
                    let resultData = await interceptor(options);
                    res.end(JSON.stringify(resultData));
                } catch (error) {
                    // 处理 JSON 解析错误
                    console.error(error)
                    res.statusCode = 500;
                    res.end(JSON.stringify({success: false,message:error.message}));
                }

            }else if (req.method === 'POST') {
                let requestData = '';

                // 监听请求数据
                req.on('data', (chunk) => {
                    requestData += chunk;
                });

                // 处理请求数据
                req.on('end', async () => {
                    try {

                        const jsonData = JSON.parse(requestData);
                        const parsedUrl = url.parse(req.url);
                        const path = parsedUrl.pathname;
                        // const query = querystring.parse(parsedUrl.query);
                        let options = {jsonData: jsonData, path: path, req: req, res: res}
                        let resultData = await interceptor(options);
                        res.end(JSON.stringify(resultData));
                    } catch (error) {
                        // 处理 JSON 解析错误
                        console.error(error)
                        res.statusCode = 500;
                        res.end(JSON.stringify({success: false,message:error.message}));
                    }
                });
            } else {
                // 处理不支持的 HTTP 方法
                res.statusCode = 405;
                res.end(JSON.stringify({error: 'Method Not Allowed'}));
            }
        });

        // const port = 3002;
        server.listen(port, () => {
            console.log(`Http Server is running on port ${port}`);
        });

    }

// // 指定服务器监听的端口号
// const port = 3002;
// server.listen(port, () => {
//     console.log(`Server is running on port ${port}`);
// });

}
